package com.cfpamf.ms.insur.pay.aspect;

import com.alibaba.fastjson.JSON;
import com.cfpamf.common.ms.exception.MSException;
import com.cfpamf.common.ms.util.DateUtil;
import com.cfpamf.ms.insur.pay.dao.PayRequestRecordMapper;
import com.cfpamf.ms.insur.pay.pojo.po.PayRequestRecordPO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.concurrent.CompletableFuture;

/**
 * @author: zhangjian
 * @date: 2019/10/9 00:08
 * @description:
 */
@Aspect
@Component
@Slf4j
public class RequestRecordLogAspect {
    @Autowired
    private PayRequestRecordMapper payRequestRecordMapper;

    @Around(value = "@annotation(com.cfpamf.ms.insur.pay.aspect.annotation.RequestRecordLog)")
    public Object doIntercept(ProceedingJoinPoint joinPoint) {
        Object object = null;
        long startTime = System.currentTimeMillis();
        try {
            object = joinPoint.proceed();
            Object finalObject = object;
            CompletableFuture.runAsync(() -> doInsertRequestRecord(joinPoint, finalObject, startTime));
        } catch (Throwable e) {
            log.error("拦截器报错", e);
        }
        return object;
    }


    private void doInsertRequestRecord(ProceedingJoinPoint joinPoint, Object object, long startTime) {
        long endTime = System.currentTimeMillis();
        String methodName = joinPoint.getSignature().getName();
        String requestJson = "";
        String responseJson = "";
        log.warn("请求体{}", String.valueOf(requestJson));

        try {
            requestJson = JSON.toJSONString(joinPoint.getArgs());
        } catch (Exception e) {
            requestJson = Arrays.toString(joinPoint.getArgs());
            log.warn("请求体解析异常", e);
        }
        try {
            responseJson = JSON.toJSONString(object);
        } catch (Exception e) {
            log.warn("响应解析异常", e);
            throw new MSException("请求体" + requestJson, "", e);
        }
        PayRequestRecordPO payRequestRecordPO = new PayRequestRecordPO();
        payRequestRecordPO.setRequestBody(requestJson);
        payRequestRecordPO.setRequestTime(DateUtil.format(DateUtil.getNow(), "yyyy-MM-dd HH:mm:ss"));
        payRequestRecordPO.setMethodName(joinPoint.getSignature().getName());
        payRequestRecordPO.setResponse(responseJson);
        payRequestRecordPO.setResponseTime(Math.toIntExact(endTime - startTime));
        payRequestRecordMapper.insert(payRequestRecordPO);
    }
}
